//
//  DBJRegistViewController.m
//  DBJ
//
//  Created by 花化华 on 2016/11/14.
//  Copyright © 2016年 itcast. All rights reserved.
//

#import "DBJRegistViewController.h"
#import "DBJLoginViewController.h"
#import <SMS_SDK/SMSSDK.h>
#import "NSString+Regular.h"
#import "SVProgressHUD.h"
#import "DBJNetworkTool.h"
#import "DBJLoginModel.h"
#import "DBJUserDefaultsTool.h"
#import "SSKeychain.h"

/** 计时出始值 */
static int timeTag = 59;

@interface DBJRegistViewController ()

@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *authCodeTextField;

@property (weak, nonatomic) IBOutlet UILabel *codeLabel;
@property (weak, nonatomic) IBOutlet UIView *codeView;

@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;

@property (weak, nonatomic) IBOutlet UIButton *protocolButton;


/** 记录接收验证码的手机号 */
@property (strong,nonatomic) NSString *phoneNumber;

@end

@implementation DBJRegistViewController

- (void)dbjSetupSubviews{
//    [super dbjSetupSubviews];
    
    //为code所在view添加点击手势
    UITapGestureRecognizer *tapGestureRecongnizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(codeViewGestureRecongnizer)];
    [_codeView addGestureRecognizer:tapGestureRecongnizer];
}

//- (void)viewWillDisappear:(BOOL)animated{
//    [super viewWillDisappear:animated];
//     [SVProgressHUD dismiss];
//}


#pragma mark - 获取验证码
/**
 * codeView的点击手势
 */
- (void)codeViewGestureRecongnizer{
    
    //获取phoneTextField的手机号
    NSString *phoneNumber = _phoneTextField.text;
    
    //判断手机号是否注册过
    if ([DBJUserDefaultsTool objetForKey:phoneNumber]) {
        [DBJTools dbjShowSVErrorTitle:@"手机号已经注册过" andTime:STANTIME];
        return;
    }
    
    //验证手机号的格式
    if ([NSString checkTelNumber:phoneNumber]) {
        
        //获取验证码
        [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:phoneNumber zone:@"86" customIdentifier:nil result:^(NSError *error) {

            if(!error){
                NSLog(@"获取验证码成功");
                [DBJTools dbjShowSVSuccessTitle:@"获取验证码成功" andTime:STANTIME];
                //记录手机号
                _phoneNumber = phoneNumber;
            }else{
                NSLog(@"错误信息,%@",error);
                [DBJTools dbjShowSVErrorTitle:@"验证码获取失败" andTime:STANTIME];
            }

        }];
        
        //更新codeLabel数据
        _codeLabel.text = [NSString stringWithFormat:@"%ds",60];
        //开启子线程、倒计时
        [self performSelectorInBackground:@selector(startTime) withObject:nil];
        //停止交互
        _codeView.userInteractionEnabled = NO;
        
    }else{
        //手机号格式错误、弹框提醒
        //--设置指示器的消失时间间隙
        [DBJTools dbjShowSVErrorTitle:@"手机号格式错误,请重新输入"andTime:STANTIME];
    }
    
}

/**
 * 开始计时
 */
- (void)startTime
{
    // 创建定时器
    NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(changeLabelText) userInfo:nil repeats:YES];
    
    // 添加到当前子线程的运行循环
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    
    //初始timeTag
    timeTag = 59;
    
    // C语言的方式开启子线程的运行循环 : C语言的方式开启,可以用C语言的方式关闭
    CFRunLoopRun();
}

/** 
 * 改变label的text
 */
- (void)changeLabelText
{
    //更新UI
    [[NSOperationQueue mainQueue]addOperationWithBlock:^{
        _codeLabel.text = [NSString stringWithFormat:@"%ds",timeTag--];
    }];

    //如果计时结束
    if (!timeTag) {
        // C语言的方式,关闭运行循环
        CFRunLoopStop(CFRunLoopGetCurrent());
        //开启交互
        _codeView.userInteractionEnabled = YES;
        //更新UI
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            _codeLabel.text = [NSString stringWithFormat:@"获取验证码"];
        }];
    }
}

#pragma mark - 按钮点击事件
/**
 * 选择协议点击事件
 */
- (IBAction)selectAgreementClick:(UIButton *)sender {
    //改变选中状态
    sender.selected = !sender.selected;
}

/**
 * 下一步
 */
- (IBAction)nextClick:(id)sender {

    //验证码
    NSString *code = _authCodeTextField.text;
    //获取phoneTextField的手机号
    NSString *phoneNumber = _phoneTextField.text;
    //获取passwordTextField的密码
    NSString *password = _passwordTextField.text;
    
    //弹框提示
    [DBJTools dbjShowSVErrorTitle:@"验证中..." andTime:60];
    
    //判断手机号是否一致
    if (![_phoneNumber isEqualToString:phoneNumber]) {
        
        [DBJTools dbjShowSVErrorTitle:@"手机号输入与验证码不匹配" andTime:STANTIME];
        
    }else if([DBJUserDefaultsTool objetForKey:phoneNumber]){//判断账号是否注册过
        
        [DBJTools dbjShowSVErrorTitle:@"手机号已经注册过" andTime:STANTIME];
        
    }else if(![NSString checkPassword:password]){//判断登录密码是否符合正则
        
        [DBJTools dbjShowSVErrorTitle:@"请输入6-18位数字和字母组合的密码" andTime:STANTIME];
        
    }else if(!_protocolButton.selected){//判断协议是否选择
        
        [DBJTools dbjShowSVErrorTitle:@"请确定是否阅读协议" andTime:STANTIME];
        
    }else{//因为Mobde无论其它条件判断成功与否、都只给验证一次，所以最后单独验证
        
        //验证验证码
        [SMSSDK commitVerificationCode:code phoneNumber:phoneNumber zone:@"86" result:^(SMSSDKUserInfo *userInfo, NSError *error) {
            
            if (!error){//注册成功
                
                [DBJTools dbjShowSVTitle:@"注册成功" andTime:STANTIME];
              
                    //模拟登录请求
                [[DBJNetworkTool sharedNetworkTool]
                 POSTWithURLString:@"http://iosapi.itcast.cn/doctor/carelinkQuickLogin.json.php"parameters:@{@"login_token" : @"985c96ce43bb5ef69de3e1ad8afaa83f"}
                 success:^(id responseObject) {
                     
                     //反序列化
                     NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:NULL];
                     
                     //如果获取成功
                     if ([result[@"msg"] isEqualToString:@"OK"]) {
                         
                         DBJLoginModel *loginModel = [DBJLoginModel loginWithDict:result[@"data"]];
                         
                         // 将密码保存到钥匙串,会自动加密.
                         /*
                          参数1 : 要保存到钥匙串的密码
                          参数2 : 保存哪个应用的密码
                          参数3 : 保存哪个账号的密码
                          */
                         NSError *error;
                         if ([SSKeychain setPassword:password forService:BUNDLEID account:phoneNumber error:&error]) {
                             //                                 NSLog(@"存储密码成功");
                             
                             //将loginModel类型变为NSData类型
                             NSData *data = [NSKeyedArchiver archivedDataWithRootObject:loginModel];
                             
                             //存储用户信息到偏好设置
                             [DBJUserDefaultsTool saveObject:data forKey:[NSString stringWithFormat:@"%@-MODEL",phoneNumber]];
                             //存储账号到偏好设置
                             [DBJUserDefaultsTool saveObject:phoneNumber forKey:phoneNumber];
                             //存储／更新当前帐号
                             [DBJUserDefaultsTool saveObject:phoneNumber forKey:CURRENTID];
                             
                             //加密存储用户名
                             [SSKeychain setPassword:phoneNumber forService:BUNDLEID account:[NSString stringWithFormat:@"%@-Account",phoneNumber] error:&error];
                             
                             //跳转登录页面
                             [self skipLoginClick:nil];
                             
                         }else{
                             NSLog(@"存储密码失败,error: %@",error);
                         }
                         
                     }else{
                         NSLog(@"获取数据失败");
                     }
                     
                 } faile:^(NSError *error) {
                     NSLog(@"网络请求失败：%@",error);
                 }];
 
            }else{
                NSLog(@"错误信息：%@",error);
                [DBJTools dbjShowSVErrorTitle:@"验证码输入有误" andTime:STANTIME];
            }
            
        }];
        
    }

}


/**
 * 已有账号，跳转登录页面
 */
- (IBAction)skipLoginClick:(id)sender {
    DBJLoginViewController *loginViewController = [[DBJLoginViewController alloc]init];
    loginViewController.title = @"登录";
    [self.navigationController pushViewController:loginViewController animated:NO];
}


@end
